package com.xin.di.uav.utils;

import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author Jerry
 * @version 1.0.0
 * @date 2018/5/14 用于发送restful请求的工具类
 */
public class HttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String sendGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String sendGet(String url) {
        return sendGet(url, null);
    }

    public static String sendPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                        paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String sendPost(String url) {
        return sendPost(url, null);
    }

    public static String sendPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
//		CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
//			httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();

            httpPost.setConfig(requestConfig);


            // 创建请求内容
            StringEntity entity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String sendPostJsonRepeat(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
//		CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
//			httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();

            httpPost.setConfig(requestConfig);
            // 创建请求内容
            StringEntity entity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("sendPostJsonRepeat error：{} ,url:{}, json:", e, url, json);
//            RepeatTaskSender.doRepeatSend(url, json); //发送不成功时，加入尝试重发策略
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String sendPostJsonRepeatProxy(String url, String json, String proxyIp, int proxyPort, Boolean isUseProxy) {
        logger.info("sendPostJsonProxy url:{},json:{},proxyIp:{},proxyPort:{}", url, json, proxyIp, proxyPort);
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
//		CloseableHttpClient httpClient = null;
        //设置代理IP、端口、协议
        HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
//			httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = null;
            if (isUseProxy) {
                requestConfig = RequestConfig.custom().setProxy(proxy)
                        .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                        .setSocketTimeout(5000).build();

            } else {
                requestConfig = RequestConfig.custom()
                        .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                        .setSocketTimeout(5000).build();
            }
            httpPost.setConfig(requestConfig);

            // 创建请求内容
            StringEntity entity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("sendPostJsonRepeatProxy error：{} ,url:{}, json:", e, url, json);
//            RepeatTaskSender.doRepeatSend(url, json); //发送不成功时，加入尝试重发策略
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


    public static byte[] sendPostJsonRepeatProxyForPicture(String url, String json, String proxyIp, int proxyPort, Boolean isUseProxy) {
        logger.info("sendPostJsonProxy url:{},json:{},proxyIp:{},proxyPort:{}", url, json, proxyIp, proxyPort);
        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//		CloseableHttpClient httpClient = null;
        //设置代理IP、端口、协议
        HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
//        CloseableHttpResponse response = null;
        byte[] resultString = null;
        try {
//			httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = null;
            if (isUseProxy) {
                requestConfig = RequestConfig.custom().setProxy(proxy)
                        .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                        .setSocketTimeout(5000).build();

            } else {
                requestConfig = RequestConfig.custom()
                        .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                        .setSocketTimeout(5000).build();
            }
            httpPost.setConfig(requestConfig);

            // 创建请求内容
            StringEntity entity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            resultString = EntityUtils.toByteArray(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("sendPostJsonRepeatProxy error：{} ,url:{}, json:", e, url, json);
        } finally {
        }
        return resultString;
    }

    public static String sendPostJsonProxy(String url, String json, String proxyIp, int proxyPort) {
        logger.info("sendPostJsonProxy url:{},json:{},proxyIp:{},proxyPort:{}", url, json, proxyIp, proxyPort);
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
//		CloseableHttpClient httpClient = null;
        //设置代理IP、端口、协议
        HttpHost proxy = new HttpHost(proxyIp, proxyPort, "https");
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
//			httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy)
                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();

            httpPost.setConfig(requestConfig);


            // 创建请求内容
            StringEntity entity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String sendPostJsonSetHeaderToken(String url, String json, String token) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
//		CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
//			httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Authorization", "Bearer " + token);
            // 创建请求内容
            StringEntity entity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String sendPostJsonSetHeader(String url, String json, String signature) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
//		CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
//			httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("signature", signature);
            // 创建请求内容
            StringEntity entity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static boolean returnResult(String resultStr) {
        if (StringUtils.isNullOrEmpty(resultStr)) {
            return false;
        } else {
            JSONObject resultObj = JSONObject.parseObject(resultStr);
            return resultObj.getBooleanValue("success");
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {

        String unpUrl = "https://api.weixin.qq.com/cgi-bin/token";
        //mavlink
//		String hexString = "FE1EA0010118FFFFAE705FB94B01889A241388F742010C3000006347CB4733489B48599CC60B";
//		String hexString = "FE21390108B400000000000000009BDF50439BDF5043B8ABCE24F3C0C934FC2C00004C9F0000000E40";
        //skylink 180#
//			String hexString ="FE21BF1A04000000000000B400000000000000000000A281C342A281C3426A1A5A2830B50000780C000097940000001482";
//			skylink 0#
        String hexString = "FE03481A0400000000000000000002120314FA";

        byte[] bytes = decode(hexString);

//        UavMessage uavMessage = new UavMessage();
//        uavMessage.setStart((short) 0x5aa5);
//        uavMessage.setClassid((byte) 0x08);
//        uavMessage.setMsgid((short) 0);
//        uavMessage.setSeq(1111);
//        uavMessage.setExtend(2222);
//        uavMessage.setTimastamp(TimeUtil.getTimestamp());
//        uavMessage.setDest(IPv4Util.ipToInt(NetUtils.getLocalHost()));
//        uavMessage.setSrc(721); //无人机信息
//        //	uavMessage.setSrc(0xFFF00000); //基站信息
//        uavMessage.setPayload(bytes);
//        uavMessage.calculateCrc();
//        uavMessage.setEnd((byte) 0x33);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("grant_type", "client_credential");
        jsonObject.put("appid", "wxe6b1552baf2f3303");
        jsonObject.put("secret", "00fc978b57673faaab9de9e96c035e7b");
//        String st = sendPostJsonRepeatProxy(unpUrl, "", "ie-uocs-out.sit.sf-express.com", 80);
        System.out.println("");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String sendGetJsonRepeatProxy(String url, String proxyIp, int proxyPort, Map<String, String> param, boolean isUseProxy) {


        HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
        RequestConfig requestConfig = null;
        if (isUseProxy) {
            requestConfig = RequestConfig.custom()
                    .setProxy(proxy)
                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();

        } else {
            requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();

        }


        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static byte[] decode(String src) {
        int m = 0, n = 0;
        int byteLen = src.length() / 2;
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + src.substring(i * 2, m)
                    + src.substring(m, n));
            ret[i] = Byte.valueOf((byte) intVal);
        }
        return ret;
    }
}
